package it.polimi.swKnights.SWIMv2.servlets.registration;

import it.polimi.swKnights.SWIMv2.ejb.exceptions.AlreadyExistingException;
import it.polimi.swKnights.SWIMv2.ejb.exceptions.InvalidConfirmationCodeException;
import it.polimi.swKnights.SWIMv2.ejb.exceptions.NotRegisteredConfirmException;
import it.polimi.swKnights.SWIMv2.ejb.registration.UserConfirmationHandlerRemote;
import it.polimi.swKnights.SWIMv2.general.Errors;
import it.polimi.swKnights.SWIMv2.servlets.SwimServlet;

import java.io.IOException;

import javax.ejb.EJBException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ConfirmRegistration
 */
public class ConfirmRegistration extends SwimServlet
{
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{

		String destination = null;
		String userName = request.getParameter("username");
		String registrationCode = request.getParameter("code");

		UserConfirmationHandlerRemote ucr = this
				.lookUp(UserConfirmationHandlerRemote.class);
		try
		{
			ucr.confirmUser(userName, registrationCode);
			request.setAttribute("wellcome", "WELLCOME " + userName + "!!");
			destination = "./userHome?status=confirmed";
		}
		catch (InvalidConfirmationCodeException e)
		{
			// redirect to home
			destination = "./siteHome?status=notconfirmed";
		}
		catch (NotRegisteredConfirmException e)
		{
			destination = "./siteHome?error="+Errors.registration;
		}
		catch (AlreadyExistingException e)
		{
			destination = "./siteHome?error="+Errors.registration;
		}
		catch(EJBException e)
		{
			destination = "./siteHome?error="+Errors.notuser;
		}

		response.sendRedirect(destination);

	}

}
